//
//  JFCityViewController.m
//  JFFootball
//
//  Created by 张志峰 on 2016/11/21.
//  Copyright © 2016年 zhifenx. All rights reserved.
//

#import "JFCityViewController.h"
#import "JFCityTableViewCell.h"
#import "JFAreaDataManager.h"
#import "JFCitySearchResultViewController.h"
#import "BDLocationServer.h"
#import "JFButton.h"
#import "BDCityInfo.h"
#import "ZMChineseConvert.h"

#define KCURRENTCITYINFODEFAULTS [NSUserDefaults standardUserDefaults]

@interface JFCityViewController () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating,UISearchControllerDelegate>
{
    NSInteger        _HeaderSectionTotal;           //头section的个数
    CGFloat          _cellHeight;                   //添加的(显示区县名称)cell的高度
    NSString         *locationCity;
    
}

@property (nonatomic, strong) UILabel *currentLabel;
@property (nonatomic, strong) JFButton *quxianButton;
@property (nonatomic, strong) UITableView *rootTableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) JFAreaDataManager *manager;

@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) JFCitySearchResultViewController *searchResultsController;

/*主要部分的数据*/
@property (nonatomic, strong) NSMutableDictionary   *sectionMutableDictionary;
/** 最近访问的城市*/
@property (nonatomic, strong) NSMutableArray *historyCityMutableArray;
/** 热门城市*/
@property (nonatomic, strong) NSArray *hotCityArray;
/** 字母索引*/
@property (nonatomic, strong) NSMutableArray *characterMutableArray;
/** 根据cityNumber在数据库中查到的区县*/
@property (nonatomic, strong) NSMutableArray *areaMutableArray;

@property (nonatomic, strong) NSMutableArray *searchDatasource;

@end

@implementation JFCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _HeaderSectionTotal = 1;
    
    [self.view addSubview:self.rootTableView];
    self.rootTableView.tableHeaderView = self.headerView;
    
    NSString *cityDataPath = [DocumentPath stringByAppendingPathComponent:@"cityData.plist"];
    NSString *sectionDataPath = [DocumentPath stringByAppendingPathComponent:@"sectionData.plist"];
    
    [self.characterMutableArray addObjectsFromArray:[NSArray arrayWithContentsOfFile:cityDataPath]];
    self.sectionMutableDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:sectionDataPath];
    
    self.historyCityMutableArray = [NSKeyedUnarchiver unarchiveObjectWithData:[KCURRENTCITYINFODEFAULTS objectForKey:@"historyCity"]];
    
    [_rootTableView reloadData];
    if (self.sectionMutableDictionary.allKeys.count == 0) {
        [self showErrorViewWithTapBlock:nil];
    }
    
    
    NSString *lastCity = [[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"];
    if ([lastCity isNotEmpty]) {
        UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 5, 25 ,25)];
        [backButton setImage:[UIImage imageNamed:@"cha"] forState:UIControlStateNormal];
        
        UIBarButtonItem *backBarButton=[[UIBarButtonItem alloc]initWithCustomView:backButton];
        self.navigationItem.leftBarButtonItem = backBarButton;
        
        [[backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    }
    if (![locationCity isNotEmpty]) {
        [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"locationFinishChangeButton" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
            locationCity = x.object;
            [self.rootTableView reloadData];
        }];
    }
}

- (void)setCurrentCityName:(NSString *)currentCityName{
    locationCity = currentCityName;
}

- (void)choseCityBlock:(JFCityViewControllerBlock)block {
    self.choseCityBlock = block;
}

- (NSMutableArray *)areaMutableArray {
    if (!_areaMutableArray) {
        _areaMutableArray = [NSMutableArray arrayWithObject:ASLocalizedString(@"全城")];
    }
    return _areaMutableArray;
}

- (UISearchController *)searchController{
    if (_searchController == nil) {
        _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = YES;
        _searchController.delegate = self;
        _searchController.searchBar.tintColor = [UIColor colorWithHexString:@"#1c1c1c"];
        _searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
        _searchController.searchBar.barTintColor = [UIColor whiteColor];
        UIImageView *barImageView = [[[_searchController.searchBar.subviews firstObject] subviews] firstObject];
        barImageView.layer.borderColor = kBDColorGray.CGColor;
        barImageView.layer.borderWidth = 1;
        _searchController.hidesNavigationBarDuringPresentation = NO;
        //这行代码在ipad下是会崩溃的，在iPhone下是需要的，否则在取消搜索的时候不会重新加载本来的数据
        if ([UIDevice currentDevice].systemVersion.floatValue > 9.1) {
            _searchController.obscuresBackgroundDuringPresentation = NO;  // 9.1  之后的方法
        }
        _searchController.dimsBackgroundDuringPresentation = NO;
        [_searchController.searchBar sizeToFit];
        _searchController.searchBar.placeholder = ASLocalizedString(@"搜索");
    }
    return _searchController;
}

- (NSMutableArray *)historyCityMutableArray {
    if (!_historyCityMutableArray) {
        _historyCityMutableArray = [[NSMutableArray alloc] init];
    }
    return _historyCityMutableArray;
}

- (NSArray *)hotCityArray {
    if (!_hotCityArray) {
        _hotCityArray = @[ASLocalizedString(@"北京市"), ASLocalizedString(@"上海市"), ASLocalizedString(@"广州市"), ASLocalizedString(@"深圳市"), ASLocalizedString(@"武汉市"), ASLocalizedString(@"天津市"), ASLocalizedString(@"西安市"), ASLocalizedString(@"南京市"), ASLocalizedString(@"杭州市"), ASLocalizedString(@"成都市"), ASLocalizedString(@"重庆市")];
    }
    return _hotCityArray;
}

- (NSMutableArray *)characterMutableArray {
    if (!_characterMutableArray) {
//        _characterMutableArray = [NSMutableArray arrayWithObjects:@"!", @"#", @"$", nil];
        _characterMutableArray = [NSMutableArray array];
    }
    return _characterMutableArray;
}

- (UIView *)headerView{
    if (!_headerView) {
        self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0)];
        _headerView.backgroundColor = [UIColor whiteColor];
        [_headerView addSubview:self.searchController.searchBar];
//        self.currentLabel = [[UILabel alloc] init];
//        
//        
//        NSString *lastCity = nil;
//        
//        
//        if ([BDLocationServer whetherOpenLocationServer] == NO) {
//            lastCity = ASLocalizedString(@"未开启定位");
//        }else{
//            BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
//            lastCity = locationModel.city;
//            
//            UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] init];
//            [_currentLabel addGestureRecognizer:tapGR];
//            [[tapGR rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
//                
//                NSDictionary *agreeArray = [NSDictionary dictionaryWithContentsOfFile:[DocumentPath stringByAppendingPathComponent:@"sectionData.plist"]];
//                BOOL haveAgreeCity = NO;
//                for (NSArray *value in agreeArray.allValues) {
//                    if ([value containsObject:locationModel.city] && [BDLocationServer whetherOpenLocationServer]) {
//                        haveAgreeCity = YES;
//                        break;
//                    }
//                }
//                if (haveAgreeCity == NO) {
//                    [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"该城市未开放，暂时没有数据，是否继续选择该城市？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"确定")] clickBlock:^(NSInteger index) {
//                        if (index == 1) {
//                            [self finishedChooseCityWithCityName:lastCity];
//                        }
//                    }];
//                }else{
//                    [self finishedChooseCityWithCityName:lastCity];
//                }
//                
//            }];
//        }
//        
//        _currentLabel.text = [NSString stringWithFormat:ASLocalizedString(@"当前所在城市：%@"), lastCity];
//        [_currentLabel sizeToFit];
//        _currentLabel.top = self.searchController.searchBar.height + 10;
//        _currentLabel.left = 10;
//        [_headerView addSubview:_currentLabel];
//        
//        self.quxianButton.size = CGSizeMake(75, 21);
//        self.quxianButton.right = _headerView.width - 20;
//        self.quxianButton.centerY = _currentLabel.centerY;
//        [_quxianButton addTarget:self action:@selector(touchUpJFButtonEnevt:) forControlEvents:UIControlEventTouchUpInside];
//        _quxianButton.imageName = @"down_arrow_icon1";
//        _quxianButton.title = ASLocalizedString(@"选择区县");
//        _quxianButton.titleColor = [UIColor colorWithRed:155 / 255.0 green:155 / 255.0 blue:155 / 255.0 alpha:1];
//        [_headerView addSubview:_quxianButton];
        
        _headerView.height = self.searchController.searchBar.height;
    }
    return _headerView;
}

- (UILabel *)currentLabel{
    if (!_currentLabel) {
        self.currentLabel = [[UILabel alloc] init];
        _currentLabel.textAlignment = NSTextAlignmentLeft;
        _currentLabel.textColor = [UIColor blackColor];
        _currentLabel.font = [UIFont boldSystemFontOfSize:14];
        _currentLabel.userInteractionEnabled = YES;
    }
    return _currentLabel;
}

- (JFButton *)quxianButton{
    if (!_quxianButton) {
        self.quxianButton = [JFButton buttonWithType:UIButtonTypeCustom];
        _quxianButton.imageName = @"down_arrow_icon1";
    }
    return _quxianButton;
}

- (void)touchUpJFButtonEnevt:(JFButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        sender.imageName = @"down_arrow_icon2";
    }else {
        sender.imageName = @"down_arrow_icon1";
    }
    if (sender.selected) {
        //如果是第一次
        NSString *lastCityId = [BDLocationServer getCityIdWithCityName:[[NSUserDefaults standardUserDefaults] objectForKey:@"lastCity"] cityType:BDCityTypeCity];
        NSArray *array = [BDCityInfo getCityArrayWithParentId:lastCityId.integerValue];
        
        for (BDCityInfo *cityInfo in array) {
            [self.areaMutableArray addObject:cityInfo.name];
        }
        if (0 == (self.areaMutableArray.count % 3)) {
            _cellHeight = self.areaMutableArray.count / 3 * 50;
        }else {
            _cellHeight = (self.areaMutableArray.count / 3 + 1) * 50;
        }
        if (_cellHeight > 300) {
            _cellHeight = 300;
        }
        
        
        //添加一行cell
        [_rootTableView endUpdates];
        [_characterMutableArray insertObject:@"*" atIndex:0];
        _HeaderSectionTotal = 4;
        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
        [self.rootTableView insertSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        [_rootTableView endUpdates];
    }else {
        //清空区县名称数组
        self.areaMutableArray = nil;
        //删除一行cell
        [_rootTableView endUpdates];
        [_characterMutableArray removeObjectAtIndex:0];
        _HeaderSectionTotal = 3;
        NSIndexSet *indexSet = [[NSIndexSet alloc] initWithIndex:0];
        [self.rootTableView deleteSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
        [_rootTableView endUpdates];
    }
}

- (UITableView *)rootTableView {
    if (!_rootTableView) {
        _rootTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _rootTableView.delegate = self;
        _rootTableView.dataSource = self;
        _rootTableView.sectionIndexTrackingBackgroundColor = [UIColor clearColor];
        _rootTableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _rootTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        [_rootTableView registerClass:[JFCityTableViewCell class] forCellReuseIdentifier:@"cityCell"];
        [_rootTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cityNameCell"];
    }
    return _rootTableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.searchController.active == YES) {
        return 1;
    }else {
        return _characterMutableArray.count + _HeaderSectionTotal;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchController.active == YES) {
        return self.searchDatasource.count;
    }else{
        if (section == 0) {
            return 1;
        }
        NSString *key = _characterMutableArray[section - 1];
        NSMutableArray *arr = self.sectionMutableDictionary[key];
        return section < _HeaderSectionTotal ? 1 : arr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchController.active == YES) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cityNameCell" forIndexPath:indexPath];
        cell.textLabel.text = self.searchDatasource[indexPath.row];
        cell.textLabel.textColor = [UIColor grayColor];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        return cell;
    }else{
        if (indexPath.section == 0) {
            JFCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cityCell" forIndexPath:indexPath];
            
            BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
            
            if ([BDLocationServer whetherOpenLocationServer] == YES) {
                if ([locationModel.city isNotBlank]) {
                    cell.cityNameArray = @[ASLocalizedString(locationModel.city)];
                }else{
                    cell.cityNameArray = @[ASLocalizedString(@"定位失败")];
                }
            }else {
                cell.cityNameArray = @[ASLocalizedString(@"未开启定位")];
            }
            
            cell.clickBlock = ^(NSString *cityName){
                
                NSDictionary *agreeArray = [NSDictionary dictionaryWithContentsOfFile:[DocumentPath stringByAppendingPathComponent:@"sectionData.plist"]];
                BOOL haveAgreeCity = NO;
                for (NSArray *value in agreeArray.allValues) {
                    if ([value containsObject:cityName] && [BDLocationServer whetherOpenLocationServer]) {
                        haveAgreeCity = YES;
                        break;
                    }
                }
                if (haveAgreeCity == NO) {
                    [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"该城市未开放，暂时没有数据，是否继续选择该城市？")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"取消")otherTitle:@[ASLocalizedString(@"确定")] clickBlock:^(NSInteger index) {
                        if (index == 1) {
                            [self finishedChooseCityWithCityName:cityName];
                        }
                    }];
                }else{
                    [self finishedChooseCityWithCityName:cityName];
                }
            
                
//                [self finishedChooseCityWithCityName:cityName];
//                //这里要判断当前的情况
//                if (_HeaderSectionTotal == 4 && indexPath.section == 0) {
//                    //全城不用理会
//                    if ([cityName isEqualToString:ASLocalizedString(@"全城")]) {
////                        __weak typeof(self) weakSelf = self;
////                        [_manager currentCity:[KCURRENTCITYINFODEFAULTS objectForKey:@"cityNumber"] currentCityName:^(NSString *name) {
////                            [KCURRENTCITYINFODEFAULTS setObject:name forKey:@"currentCity"];
////                            weakSelf.currentLabel.text = [NSString stringWithFormat:ASLocalizedString(@"当前：%@"), name];
////                            [weakSelf.currentLabel sizeToFit];
////                            if (weakSelf.choseCityBlock) {
////                                weakSelf.choseCityBlock(name);
////                            }
////                        }];
//                    }else{
//                        //这里是处理区县的地方
//                    }
//                }else {
//                    //        [[BDLocationServer sharedServer] locatonWithCityName:cityName];
//                    self.currentLabel.text = [NSString stringWithFormat:ASLocalizedString(@"当前：%@"), cityName];
//                    [self.currentLabel sizeToFit];
//                    [KCURRENTCITYINFODEFAULTS setObject:cityName forKey:@"currentCity"];
//                    
//                    if (self.choseCityBlock) {
//                        self.choseCityBlock(cityName);
//                    }
//                    [_manager cityNumberWithCity:cityName cityNumber:^(NSString *cityNumber) {
//                        [KCURRENTCITYINFODEFAULTS setObject:cityNumber forKey:@"cityNumber"];
//                    }];
//                    
//                    [self historyCity:cityName];
//                }
//                [self dismissViewControllerAnimated:YES completion:nil];
            };
            
            return cell;
        }else {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cityNameCell" forIndexPath:indexPath];
            NSString *key = _characterMutableArray[indexPath.section - 1];
            NSMutableArray *currentArray = self.sectionMutableDictionary[key];
            cell.textLabel.text = ASLocalizedString(currentArray[indexPath.row]);
            cell.textLabel.textColor = [UIColor grayColor];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            return cell;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.searchController.active == YES) {
        return 44;
    }else {
        if (_HeaderSectionTotal == 4 && indexPath.section == 0) {
            return _cellHeight;
        }else {
            return 44;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.searchController.active == YES) {
        return 0;
    }else {
//        if (_HeaderSectionTotal == 4 && section == 0) {
//            return 0;
//        }else{
//            return 40;
//        }
        return 40;
    }
}
//
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (self.searchController.active == YES) {
        return nil;
    }else {
        if (section == 0) {
            return ASLocalizedString(@"定位城市");
        }
        
        return _characterMutableArray[section - 1];
//        if (_HeaderSectionTotal == 3) {
//            switch (section) {
//                case 0:
//                    return ASLocalizedString(@"定位城市");
//                    break;
//                case 1:
//                    return ASLocalizedString(@"最近访问的城市");
//                    break;
//                case 2:
//                    return ASLocalizedString(@"热门城市");
//                    break;
//                default:
//                    return _characterMutableArray[section];
//                    break;
//            }
//        }else {
//            switch (section) {
//                case 1:
//                    return ASLocalizedString(@"定位城市");
//                    break;
//                case 2:
//                    return ASLocalizedString(@"最近访问的城市");
//                    break;
//                case 3:
//                    return ASLocalizedString(@"热门城市");
//                    break;
//                default:
//                    return _characterMutableArray[section];
//                    break;
//            }
//        }
    }
}

//设置右侧索引的标题，这里返回的是一个数组哦！
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (self.searchController.active == YES) {
        return nil;
    }else {
        return _characterMutableArray;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [self finishedChooseCityWithCityName:cell.textLabel.text];
    
}

- (void)finishedChooseCityWithCityName:(NSString *)cityName{
    
    [KCURRENTCITYINFODEFAULTS setObject:cityName forKey:@"currentCity"];
    [_manager cityNumberWithCity:cityName cityNumber:^(NSString *cityNumber) {
        [KCURRENTCITYINFODEFAULTS setObject:cityNumber forKey:@"cityNumber"];
    }];
    if (self.choseCityBlock) {
        self.choseCityBlock(cityName);
    }
    [self historyCity:cityName];
    if (self.searchController.active) {
        [self.searchController setActive:NO];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)willPresentSearchController:(UISearchController *)searchController{

}

- (void)willDismissSearchController:(UISearchController *)searchController{

}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *key = [ZMChineseConvert convertTraditionalToSimplified:searchController.searchBar.text] ;
    
    NSMutableArray *datasource = [NSMutableArray array];
    for (NSString *cityFirstLetter in self.sectionMutableDictionary) {
        NSArray *litArray = self.sectionMutableDictionary[cityFirstLetter];
        for (NSString *cityName in litArray) {
            if ([cityName containsString:key]) {
                [datasource addObject:cityName];
            }
        }
    }
    self.searchDatasource = datasource;
    [self.rootTableView reloadData];
}


/// 添加历史访问城市
- (void)historyCity:(NSString *)city {
    //避免重复添加，先删除再添加
    [_historyCityMutableArray removeObject:city];
    [_historyCityMutableArray insertObject:city atIndex:0];
    if (_historyCityMutableArray.count > 3) {
        [_historyCityMutableArray removeLastObject];
    }
    NSData *historyCityData = [NSKeyedArchiver archivedDataWithRootObject:self.historyCityMutableArray];
    [KCURRENTCITYINFODEFAULTS setObject:historyCityData forKey:@"historyCity"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
